<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\middleware\api;

use think\Request;

/**
 * 接口日志中间件
 * Class SystemLog
 * @package app\api\middleware
 */
class ApiLog
{

    /**
     * 敏感信息字段，日志记录时需要加密
     * @var array
     */
    protected $sensitiveParams = [];

    public function handle(Request $request, \Closure $next)
    {
        $params = $request->param();
        if (isset($params['s'])) {
            unset($params['s']);
        }
        foreach ($params as $key => $val) {
            in_array($key, $this->sensitiveParams) && $params[$key] = "***********";
        }
        $method = strtolower($request->method());
        $url = $request->url();

        trace([
            'url'    => $url,
            'method' => $method,
            'params' => $params,
        ],
            'requestDebugInfo1'
        );

        if ($request->isPost()) {
            $data = [
                'url'         => $url,
                'method'      => $method,
                'ip'          => request()->ip(),
                'content'     => json_encode($params, JSON_UNESCAPED_UNICODE),
                'userAgent'   => $_SERVER['HTTP_USER_AGENT'],
                'createTime' => time(),
            ];

            \think\facade\Log::write('api请求日志:'.json_encode($data,JSON_UNESCAPED_UNICODE));
        }
        return $next($request);
    }

}